import enum_data.FormStatus;

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.TreeMap;

public class Form_User extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField txtFld_FIO;
    private JTextField txtFld_Login;
    private JComboBox cmbBx_Doljnost;
    private JPasswordField psswd2;
    private JPasswordField psswd1;
    private String userID;
    private TreeMap <Integer, String> categoryMap = new TreeMap<Integer, String>();

    public FormStatus formMode;


    public Form_User(String userID, FormStatus formMode) throws SQLException {

        setContentPane(contentPane);
        setModal(true);
//        setAlwaysOnTop(true);
        setResizable(false);
        this.pack();

        this.userID = userID;
        this.formMode = formMode;

        ResultSet doljnostList = null;
        ResultSet userData = null;

        if (formMode == FormStatus.EDIT){
            txtFld_Login.setEditable(false);
            txtFld_Login.setToolTipText("Поле 'Логин' доступно только для чтения");

            try {
                userData = TEDatabase.execQuery("SELECT user.id, user.login, user.privilegie, privilegie.privilegie_name, user.fio, user.password " +
                        "FROM user INNER JOIN privilegie ON user.privilegie = privilegie.id WHERE user.id=" + userID);
                userData.next();

                txtFld_Login.setText(userData.getString("login"));
                txtFld_FIO.setText(userData.getString("fio"));
                psswd1.setText(userData.getString("password"));
                psswd2.setText(userData.getString("password"));

            } catch (SQLException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }

        //Размещаем окно по центру экрана
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int locationX = (screenSize.width - 300) / 2;
        int locationY = (screenSize.height - 100) / 2;
        setBounds(locationX, locationY, getWidth(), getHeight());

        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        //endregion заполняем форму даными (кроме combobox)

        cmbBx_Doljnost.removeAllItems();
        categoryMap.clear();
        String name = null;

        try {
            doljnostList = TEDatabase.execQuery("SELECT privilegie.id, privilegie_name FROM tradexpert.privilegie;");

            while (doljnostList.next()) {
                name = doljnostList.getString("privilegie_name");
                cmbBx_Doljnost.addItem(name);
                categoryMap.put(doljnostList.getInt("id"), name);
            }

            if (formMode == FormStatus.NEW){
                cmbBx_Doljnost.setSelectedIndex(-1);
            }else {
            cmbBx_Doljnost.setSelectedItem(userData.getString("privilegie_name"));
            }

        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        psswd1.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent caretEvent) {
                testFormField();
            }
        });
        psswd2.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent caretEvent) {
                testFormField();
            }
        });
        txtFld_FIO.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent caretEvent) {
                testFormField();
            }
        });
        txtFld_Login.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent caretEvent) {
                testFormField();
            }
        });
        cmbBx_Doljnost.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                testFormField();
            }
        });
    }

    private void testFormField(){
        boolean incorrectFormData = false;

        // Проверяем ввод ФИО
        if (txtFld_FIO.getText().length() > 1){
            txtFld_FIO.setBackground(Color.white);
        }
        else {
            txtFld_FIO.setBackground(Color.pink);
            incorrectFormData = true;
        }

        // Проверяем ввод логина
        if (formMode == FormStatus.NEW){
            if (txtFld_Login.getText().length() > 1){
                txtFld_Login.setBackground(Color.white);
            } else {
                txtFld_Login.setBackground(Color.pink);
                incorrectFormData = true;
            }
        }

        //Проверяем ввод паролей
        String password1 = new String(psswd1.getPassword());
        String password2 = new String(psswd2.getPassword());

        if (password1.equals(password2)) {
            psswd1.setBackground(Color.white);
            psswd2.setBackground(Color.white);
        }
        else {
            psswd1.setBackground(Color.pink);
            psswd2.setBackground(Color.pink);
            incorrectFormData = true;
        }

        //Проверяем выбор должности
        if (cmbBx_Doljnost.getSelectedIndex() == -1){
            incorrectFormData = true;
        }


        if (incorrectFormData){
            buttonOK.setEnabled(false);
        } else {
            buttonOK.setEnabled(true);
        }
    }

    private void onOK() {

        String privilegieID = null;

        //Получаем id выбрранного элемента cmbBox
        for (Map.Entry<Integer, String> entry : categoryMap.entrySet()) {
            if (entry.getValue().equals(cmbBx_Doljnost.getSelectedItem())) {
                privilegieID = entry.getKey().toString();
            }
        }

    //Сохранение полей формы в БД
        String psswd = new String(psswd1.getPassword());
        String queryUpdate;

        if (formMode == FormStatus.NEW){
            queryUpdate = "INSERT INTO tradexpert.user (login, password, privilegie, fio) " +
                    "VALUES ('" + txtFld_Login.getText() + "', '" + psswd + "', '" + privilegieID + "', '"+ txtFld_FIO.getText() + "')";
        }else {
            queryUpdate = "UPDATE tradexpert.user SET login='" + txtFld_Login.getText() + "', fio='" + txtFld_FIO.getText() +
                    "', privilegie='" + privilegieID + "', password='" + psswd + "' WHERE id='" + userID.toString() + "'";
        }
        try {
            TEDatabase.updateDB(queryUpdate);
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Ошибка добавления пользователя - " + e.getMessage());
            txtFld_Login.setBackground(Color.pink);
            txtFld_Login.requestFocus();
            buttonOK.setEnabled(false);
            return;
        }
        dispose();

    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }
}
